/**
*  Copyright 2009-2015 by WWW.KNET.CN  All rights reserved.
*/
package cn.knet.sp.ncrm.common.websocket;

import java.io.IOException;
import java.util.ArrayList;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.Resource;

import cn.knet.sp.ncrm.modules.office.notify.service.OfficeNotifyRecordService;
import cn.knet.sp.ncrm.modules.sys.user.entity.User;

/**
 * TODO(websocket推送消息)
 * @author Gehaiyang
 * @date 2015年7月13日 下午2:48:26
 * 
 */
@Component
public class SystemWebSocketHandler implements WebSocketHandler {
	 
    private static final Logger logger;
 
    //所有在线用户
    private static final ArrayList<WebSocketSession> onLineUsers;
 
    static {
        onLineUsers = new ArrayList<WebSocketSession>();
        logger = LoggerFactory.getLogger(SystemWebSocketHandler.class);
    }
 
    @Resource
    private OfficeNotifyRecordService officeNotifyRecordService;
    
    /**
     * 打开链接后执行的方法
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        logger.debug("connect to the websocket success......");
        onLineUsers.add(session);
        User user  = (User) session.getAttributes().get("user");
        if(user != null){
        	
            //查询未读消息
            int count = officeNotifyRecordService.getUnreadCount(user);
            logger.debug("Query data success,has ({}) record ......",count);
            session.sendMessage(new TextMessage(count + ""));
        }
    }
 
    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        //sendMessageToUsers();
    }
 
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        if(session.isOpen()){
            session.close();
        }
        logger.debug("websocket connection closed......");
        onLineUsers.remove(session);
    }
 
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        logger.debug("websocket connection closed......");
        onLineUsers.remove(session);
    }
 
    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
 
    /**
     * 给所有在线用户发送消息
     *
     * @param message
     */
    public void sendMessageToUsers(TextMessage message) {
        for (WebSocketSession onLineUser : onLineUsers) {
            try {
                if (onLineUser.isOpen()) {
                    onLineUser.sendMessage(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    /**
     * 给某个用户发送消息
     *
     * @param User
     * @param message
     */
    public void sendMessageToUser(User goalUser, TextMessage message) {
        for (WebSocketSession onLineUser : onLineUsers) {
        	User tempUser =  (User) onLineUser.getAttributes().get("user");
            if (tempUser.getId().equals(goalUser.getId())) {
                try {
                    if (onLineUser.isOpen()) {
                        onLineUser.sendMessage(message);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            }
        }
    }
}
